import Vue from 'vue'
import Router from 'vue-router'

import AppView from '@/pages/app-view'

Vue.use(Router)
const page = name => () => import('@/pages/' + name)

export const constantRouterMap = [
  {
    path: '',
    component: AppView,
    children: [
      {path: '/404', name: '404', component: page('404'), meta: {title: '404'}},
      {path: '/500', name: '500', component: page('500'), meta: {title: '500'}},
      {path: '/drawAreaLayout', name: 'drawAreaLayout', component: page('areaLayout/DrawAreaLayout'), meta: {title: 'menu.drawAreaLayout', noCache: true}}
    ]
  },
  {path: '*', redirect: {name: '404'}}
]

export default new Router({
  // mode: 'history',
  routes: []
})

/**
 * 动态添加路由
 * @param treeData
 * @returns {Array}
 */
export function generateRouters (treeData) {
  let routers = []
  function pushData (item) {
    let accessCode = (item.accessCode).replace(/[.]/g, '_')
    let path = ''
    if (item.parentAccessCode !== undefined && item.parentAccessCode !== '' && item.parentAccessCode !== 'dashboard') {
      path = item.parentAccessCode + '/'
    }
    return {
      path: '/' + accessCode,
      name: accessCode,
      component: page(path + accessCode),
      meta: {
        title: 'menu.' + accessCode,
        parentAccessCode: item.parentAccessCode
      }
    }
  }
  function reader (children) {
    if (children && children.length !== 0) {
      children.forEach(child => {
        let router = pushData(child)
        if (child.children && child.children.length > 0) {
          router['redirect'] = (child.children[0].accessCode).replace(/[.]/g, '_')
        }
        routers.push(router)
        reader(child.children, router)
      })
    }
  }
  reader(treeData, {})
  return routers
}
